package com.freesun.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freesun.shop.entity.UserAddr;
import com.freesun.shop.mapper.UserAddrMapper;
import com.freesun.shop.service.UserAddrService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 用户配送地址 服务实现类
 * </p>
 *
 * @author zf
 * @since 2019-11-13
 */
@Service
public class UserAddrServiceImpl extends ServiceImpl<UserAddrMapper, UserAddr> implements UserAddrService {

    private static final Logger log = LoggerFactory.getLogger(UserAddrServiceImpl.class);
    @Autowired
    private UserAddrMapper userAddrMapper ;

    @Override
    public List<UserAddr> findList(String userId) {
        log.info("查询用户{}的收货地址",userId);
        List<UserAddr> userAddrs = userAddrMapper.selectList(
                new LambdaQueryWrapper<UserAddr>().
                        eq(UserAddr::getUserId, userId).eq(UserAddr::getStatus, 1)
        );
        return userAddrs;
    }

    @Override
    public void updateDefault(Long id) {
        QueryWrapper<UserAddr> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("common_addr", 1);
        UserAddr userAddrDb = userAddrMapper.selectOne(queryWrapper);
        if (null != userAddrDb) {
            userAddrDb.setCommonAddr(0);
            userAddrMapper.updateById(userAddrDb);
        }
        UserAddr userAddr=new UserAddr();
        userAddr.setAddrId(id);
        userAddr.setCommonAddr(1);
        userAddrMapper.updateById(userAddr);
    }

    @Override
    public boolean removeById(Serializable id) {
        log.info("删除收货地址{}",id);
        UserAddr userAddr = getById(id);
        if(userAddr==null) {
            throw new RuntimeException("要删除的数据不存在！");
        }
        userAddr.setStatus(0);
        userAddr.setUpdateTime(LocalDateTime.now());
        return updateById(userAddr);
    }

    @Override
    public UserAddr getUserDefaultAddr(String userId) {
        UserAddr userAddr = userAddrMapper.selectOne(new LambdaQueryWrapper<UserAddr>()
                .eq(UserAddr::getUserId, userId)
                .eq(UserAddr::getCommonAddr, 1));
        return userAddr;
    }
}

